<template>
	<view style="height: 100%;">
		
		<canvas 
			canvas-id="myCanvas" 
			id="myCanvas"
			@touchstart="handleTouchStart"
			@touchmove="handleTouchMove"
			@touchend="handleTouchEnd"
			>
			<!-- <image src="../../static/images/1.jpg"></image> -->
			
			</canvas>
		<view class="btnBox">
			
			<view @click="selectImage">添加图片</view>
		</view>	
		<view class="rotate">
			<view @click="rotateImages">旋转图片</view>
		</view>	
		
		<button type="default" @click="downLoadImg()">保存至相册</button>
	</view>
</template>

<script>
	export default {
		data(){
			return{
				ctx:'',
				beginX:'',
				beginY:'',
				movedX:'',
				movedY:'',
				layers:[],
				url: '/static/images/logo.png',
				url2: '/static/images/rotate.png',
				tempFilePath: '',
			}
		},
		onLoad() {
			this.ctx = uni.createCanvasContext('myCanvas')
		},
		methods:{
			selectImage(){
				// uni.chooseImage({
				// 	success:(res)=> {
				// 		let layer = {
				// 			type:'photo',
				// 			resoure:res.tempFilePaths[0],
				// 			x:0,
				// 			y:0,
				// 			w:200,
				// 			h:150,
				// 			isDrag:false
				// 		}
				// 		this.layers.push(layer)
				// 		this.darwImages(res.tempFilePaths[0],layer.x,layer.y,layer.w,layer.h)
				// 	}
				// })
				
				let layer = {
					type:'photo',
					resoure:this.url,
					x:0,
					y:0,
					w:200,
					h:150,
					isDrag:false
				}
				this.layers.push(layer)
				// this.darwImages(this.url,layer.x,layer.y,layer.w,layer.h)
				this.darwImages(this.url,layer.x,layer.y,200,200, -10000, -10000, 1500, 1500)
				
			},
			darwImages(url,x,y,w,h){
				this.ctx.drawImage(url,x+50,y+50,w,h)
				
				this.ctx.drawImage(this.url2,x+245,y+36,16,16)
				
				// this.ctx.draw(true)
				
				this.ctx.draw(true, () => {
				    setTimeout(() => {
				        uni.canvasToTempFilePath({
				            canvasId: 'myCanvas',
				            fileType: 'jpg',
				            success: (res) => {
				                this.tempFilePath = res.tempFilePath
				                //#ifdef H5
				                this.needLongTapSaveImg = true;
				                //#endif
				            }
				        })
				    })
				})
			},
			rotateImages(){
				console.log(1)
				// this.ctx.rotate(-Math.PI/4)
				
				// this.ctx.strokeRect(100, 10, 150, 100)
				// this.ctx.clearRect(0,0,750,900)
				this.ctx.rotate(Math.PI / 60)
				this.darwImages(this.url,this.layers.x,this.layers.y,this.layers.w,this.layers.h)
				this.ctx.draw(true)
			},
			handleTouchStart(e){
				let {x,y} = e.changedTouches[0]
				this.beginX = x
				this.beginY = y
				for (var i=this.layers.length-1;i>=0;i--) {
					if(x>this.layers[i].x && y>this.layers[i].y && x<this.layers[i].w+this.layers[i].x && y<this.layers[i].h+this.layers[i].y){
						this.layers[i].isDrag = true
						let selectObj = this.layers[i]
						this.layers.splice(i,1)
						this.layers.push(selectObj)
						console.log(selectObj)
						break
					}
				}
			},
				
			handleTouchMove(e){
				if(this.layers.length != 0 && this.layers[this.layers.length-1].isDrag == true){
					let {x,y} = e.changedTouches[0]
					this.movedX = x-this.beginX
					this.movedY = y-this.beginY
					this.layers[this.layers.length-1].x += this.movedX
					this.layers[this.layers.length-1].y += this.movedY
					this.beginX = x
					this.beginY = y
				}
				this.ctx.clearRect(0,0,750,900)
				this.layers.forEach(l=>this.darwImages(l.resoure,l.x,l.y,l.w,l.h))
			},
			handleTouchEnd(e){
				if(this.layers.length != 0){
					this.layers[this.layers.length-1].isDrag = false
				}
			},
			
			downLoadImg: function() {
				uni.canvasToTempFilePath({
				  // x: 100,
				  // y: 200,
				  // width: 50,
				  // height: 50,
				  // destWidth: 100,
				  // destHeight: 100,
				  canvasId: 'myCanvas',
				  success: function(res) {
				    // 在H5平台下，tempFilePath 为 base64
				    console.log(res.tempFilePath)
					// this.tempFilePath = res.tempFilePath
					
					
				
					
					uni.downloadFile({
						url: res.tempFilePath, //仅为示例，并非真实的资源
						success: (res) => {
							console.log(res)
							if (res.statusCode === 200) {
								var oA = document.createElement("a");
												oA.download = '111'; // 设置下载的文件名，默认是'下载'
												oA.href = res.tempFilePath;
												document.body.appendChild(oA);
												oA.click();
												oA.remove(); // 下载之后把创建的元素删除
								// console.log('下载成功');
								// uni.saveImageToPhotosAlbum({
								//     filePath: res.tempFilePath,
								//     success: function() {
								//         uni.showToast({
								//             title: '已保存至相册',
								//             icon: 'none'
								//         })
										
										
								//     }
								// });
							}
						}
					});
					
				  } 
				})
				
			    // if(this.tempFilePath == ''){
			    //     uni.showToast({
			    //         title: '图片未生成',
			    //         icon: 'none'
			    //     })
			    //     return;
			    // }
			    // //#ifndef H5
			    // uni.saveImageToPhotosAlbum({
			    //     filePath: this.tempFilePath,
			    //     success: function() {
			    //         uni.showToast({
			    //             title: '已保存至相册',
			    //             icon: 'none'
			    //         })
			    //     }
			    // });
			    // //#endif
			    // //#ifdef H5
			    // uni.showToast({
			    //     title: '请长按图片-保存至相册'
			    // })
			    // //#endif
			},
			
			imgType(ty) {
			        let type = ty.toLowerCase().replace(/jpg/i, 'jpeg');
			        var r = type.match(/png|jpeg|bmp|gif/)[0];
			        return 'image/' + r;
			    },
			
			download() {
				uni.canvasToTempFilePath({
				  x: 100,
				  y: 200,
				  width: 50,
				  height: 50,
				  destWidth: 100,
				  destHeight: 100,
				  canvasId: 'myCanvas',
				  success: function(res) {
				    // 在H5平台下，tempFilePath 为 base64
				    console.log(res.tempFilePath)
				  } 
				})
			
			//         let type = 'png';   //设置下载图片的格式
			
			//         let img_png_src = this.ctx.toDataURL("image/png");  //将canvas保存为图片
			
			//         let imgData = img_png_src.replace(imgType(type),'image/octet-stream');
			
			//         let filename = '图片' + '.' + type; //下载图片的文件名
			
			//         saveFile(imgData,filename);
			    },
			
			    saveFile(data, fileName){
			        let save_link = document.createElement('a');
			        save_link.href = data;
			        save_link.download = fileName;
			
			        let event = document.createEvent('MouseEvents');
			        event.initEvent("click", true, false);
			        save_link.dispatchEvent(event);
			    }

		}
	}
</script>

<style>
	.btnBox{
		position: fixed;
		left: 0;
		top: 0;
	}
	.rotate{
		position: fixed;
		right: 0;
		top: 0;
	}
	
	#myCanvas{
		/* width: 750rpx;
		height: 900rpx; */
		width: 100%;
		height: 100%;
		background-color: red;
	}
	.uni-page-head{
		display: none !important;
	}
</style>
